classdef spyfilt_plane < spyview_filter
   properties (Constant=true)
       name='Plane';
       description='Subtract a plane a*x + b*y + c from the data';
       parameters=struct('name',{'a','b','c','Average','Median'},'type',{'float','float','float','button','button'},'default',{0,0,0,0,0},'min',{-.1,-.1,-.1,-1,-1},'max',{.1,.1,.1,1,1});
   end
   methods
       function [pm,px,py]=filter(sf,pm,px,py)
           [x,y]=meshgrid(px,py);
           pm=pm-sf.values{1}*x-sf.values{2}*y-sf.values{3};           
       end
       
       function sf=button(sf,i, sv,ind)
           if ind > 0 
             en=sv.filters{ind}.enabled;
             if en
                 sv.filters{ind}.enabled=0;
                 sv.runFilters;
             end
           end
           switch(i)
               case 4
                   pm=sv.pm;
                   n=length(sv.px);
                   sxx=sum(sv.px(:).^2) - (sum(sv.px(:))^2)/n;
                   sxz = sum(sv.px(:).*nanmean(pm,1)') - (sum(sv.px(:))*sum(nanmean(pm,1)))/n;
                   
                   n=length(sv.py);
                   syy=sum(sv.py(:).^2) - (sum(sv.py(:))^2)/n;
                   syz = sum(sv.py(:).*nanmean(pm,2)) - (sum(sv.py(:))*sum(nanmean(pm,2)))/n;
                   
                   sf.values{1}=sxz/sxx;
                   sf.values{2}=syz/syy;
                   [x,y]=meshgrid(sv.px,sv.py);
                   sf.values{3}=mean(pm(:)-(x(:)*sf.values{1}+y(:)*sf.values{2}));                   
               case 5
                   dx=(diff(sv.pm,[],2))/(sv.px(2)-sv.px(1));
                   dy=(diff(sv.pm,[],1))/(sv.py(2)-sv.py(1));
                   dx=nanmedian(dx(:));
                   dy=nanmedian(dy(:));                   
                   sf.values{1}=dx;
                   sf.values{2}=dy;
                   [x,y]=meshgrid(sv.px,sv.py);
                   sf.values{3}=nanmean(sv.pm(:)-(x(:)*sf.values{1}+y(:)*sf.values{2}));
           end
           if ind && en == 1
              sv.filters{ind}.enabled=1;
              sv.runFilters;
           end
       end
   end
end